import { observable, action, toJS,asMap } from 'mobx';
import { Comment, Reply, AtSomeone, SearchAdvanced } from 'weaver-mobile-page';
import { Tools, Modal, Toast } from 'weaver-mobile';
import Adapter from '../adapter/index';
import * as AdapterConstant from '../constants/adapter';
import base from '../util/base';
import * as API from '../apis/communicateApi';
import * as API_REQ from '../apis/form';
import remove from 'lodash/remove';
import includes from 'lodash/includes';
// import * as SignUtil from '../util/SignUtil';
import * as CommunicateUtil from '../util/CommunicateUtil';
import { Base64 } from 'js-base64';
const getLabel = Tools.getLabel;
const alert = Modal.alert;
export class CommunicateStore {
  
  
  @observable initParams = {};
  @observable communicationId = 0; 
 
  @observable clickedCommunicateTab = false;  
  @observable hasRelatedMsg = false; 
  @observable hasSubmitRight = false;
  @observable page = 'allCommunications'; //默认全部为首页 与我相关relatedMe 相关资源relatedResource
  @observable type = 'list'; // type类型为 全部：list， 与我相关： relatedme  相关资源： resource (主要用于params)
  @observable replyType = ''; //回复的类型，作为新建的交流，还是引用 quote，还是评论comment
  @observable relatedPage = 1; //全部、与我相关页面请求加载第几页的数据

  @observable relatedAdSearch = null; //高级搜索
  @observable adSearchCondition = [];
  @observable path = ''; //高级搜索的路径


   //回复组件左侧默认按钮
    leftConfig = [
    { type: 'blog-biaoqing' },
    { type: 'blog-tupian' },
    { type: '@' },
  ];

  @observable placeholderValue= getLabel(512567, '交流内容...'); 
  @observable communicateReply = {}; //创建相关交流组件
  @observable commentReplyStoreMap = {}; //评论回复组件
  @observable quoteReplyStoreMap = {}; //引用回复组件

  @observable replyComment = null;
  @observable replyDatas = {}; // reply 组件+号内部回显数据
  @observable communicateReplyVisible = null; //设置reply组件显隐
  @observable needAttachBtn = false; //是否需要回复组件底部的添加按钮
  @observable hasLoaded = false;   
  @observable signRelyFlag = false; //签字意见回复flag
  
  @observable reflashCurrentPageFlag = false; //是否需要刷新当前页面


  @observable imageArr = [];
  @observable atUserStore = new AtSomeone.Store({route:'/req',id:'remarkat'});

  @observable commentReplyListMap = observable.map ? observable.map({}) : asMap({});
  @observable allComment = new Comment.Store({
    getComment: this.getContentList.bind(this, {}, this.commentReplyListMap),
    operate: this.getDetailOperate,
    getChild: this.getChild,
  });

  @observable relatedMeComment = new Comment.Store({
    getComment : this.getContentList.bind(this, {}, this.commentReplyListMap),
    operate: this.getDetailOperate,
    getChild: this.getChild
  })
  @action getComment = () => (
    new Promise((resolve) => {
      resolve({
        replyList: this.getParentReplyDatas(),
        hasMore: false, // 加载到最后一页的时候返回
      });
    })
  )



  @observable needPanel = false;
  @observable quoteInfo = {}; //点击某条交流引用按钮，回调的信息
  @observable quoteCancelFlag = false; //引用他人交流取消标志
  reqOperators = []; //@相关的数据

  @action('获取全部数据列表')
  getContentList = (newparams) => {
    let params = {};
    const relatedAdSearchParams = this.relatedAdSearch.form.formParams;
    let sendType = this.type == 'list'?  'list' : 'relatedme';
    let baseParams =  {
      type: sendType,
      communicationId: this.communicationId, 
      ...this.initParams,
      ...newparams,
    }
    if(this.type !== 'relatedme') {
      baseParams = {...baseParams,  ...relatedAdSearchParams}
    }
    if(this.reflashCurrentPageFlag) { 
      this.reflashCurrentPageFlag = false;
      params = {...baseParams, currentPage: this.relatedPage-1,}
    } else {
      params = {...baseParams,  currentPage: this.relatedPage++, }
    }
    let map = this.commentReplyListMap;
    return  API.getContentList(params).then(res => {
      res.replyList.map(v => {
        let str = '';
        map.set(parseInt(v.contentId), v.childReply);
        v.childReply = v.childReply.slice(0,5);
        if(v.quoteInfo && v.quoteInfo.content) {
          str = CommunicateUtil.getRemarkHtml(Base64.decode(v.quoteInfo.content));
          v.quoteInfo.content =  Base64.encode(str);
        } 
         if(v.childReply.length !== 0) {
            v.childReply.map(item => {
              str = CommunicateUtil.getRemarkHtml(item.remark);
              item.content = Base64.encode(str);
            });
        } 
        str = CommunicateUtil.getRemarkHtml(Base64.decode(v.content));
        v.content  = Base64.encode(str);
      })
      return res;
    })
  }
  @action('获取子回复')
  getChild = (data) => {
    let list = [], replylist = [];
    let contentId = data.data.contentId;
    if(this.commentReplyListMap.has(contentId)) {
     list = this.commentReplyListMap.get(contentId);
    }
   return new Promise((resolve) => {
      resolve({
        replyList: toJS(list)
      });
    })
  }


  /*************************************初始化****************************** */
  inital = () => {
    this.initAdSearch(); 
    this.getResource();
    this.initAtData();
  }

  @action('store中属性修改方法') 
  comSetStoreState = (params) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    })
  }
  
  @action('初始获取params')
  init = (params = {}) => {
   const baseParamKey = ["requestid",  "workflowid", "f_weaver_belongto_userid",
       "f_weaver_belongto_usertype",'authStr', 'authSignatureStr', 'isurger'];
   baseParamKey.map(v => {
       this.initParams[v] = params[v];
   });
   this.getInitParams(this.initParams); 
 } 

 @action getInitParams = (params = {}) => {
   API.getInitParams(params).then( res => {
    this.communicationId = res.communicationId;
    this.hasRelatedMsg = res.hasRelatedMsg;
    this.hasSubmitRight = res.hasSubmitRight;
    if (res.attachList && res.attachList.length > 0) {
      this.needAttachBtn = true;  
      if(!this.hasLoaded) {
        this.setBottomButton();
      }
      this.communicateReply = new Reply.Store({
        getAttachList: this.getReplyAttachList, 
      }); //新建交流reply
      this.hasLoaded = true; //这行语句一定要放在new Reply之后！
      } else {
      this.communicateReply = new Reply.Store(); 
      this.hasLoaded = true;
      }
   })
 }

 getAtConfig = () => {
  return new Promise((resolve) => {
    resolve({
      atConfig: {
        key: 'at',
        path: '/req',
        config: {
          type: 1,
          isSingle: false,
        },
      },
    });
  })
 }
 /******************************************高级搜索********************************************************* */
  initAdSearch = () => {
    this.relatedAdSearch = new SearchAdvanced.Store({
      route: this.path,
      id: 'communicateSearch'
    });
    this.relatedAdSearch.getData({
      url:`/api/workflow/communication/getAdSearchCondition`,
      method: `GET`,
      params: {},
    })
   
  }
  @action('高级搜索提交处理')
  onRelatedSearch = () => {
      this.relatedPage = 1;
      if(this.page === 'allCommunications'){
        this.allComment.getDatas(); // 刷新列表重新渲染数据
      }else{
        this.relatedMeComment.getDatas();
      }
    }
    @action('相关交流高级搜索清空')
    onReset = () => {
      this.relatedAdSearch.form.resetFields();
    }

  /**************************************************签字意见回复 **********************************************/
  @observable replyParams={}; //回复保存传递的参数
  @observable signReplyText= '';

  @action('保存被回复人的签字意见文本') 
  setReplyMark = (text) => {
    this.signReplyText = text;
  }
  @action setSignReplyParam = (data) => {
    const baseParams =  [
      "displayname",
      "log_operatedate",
      "log_operatetime",
      "log_nodename",
      "operationname",
      "displayid", 
      "displaydepname", 
      "displaydepid",
      "logid"
    ];
    baseParams.map(v => {
      this.replyParams[v] = data[v];
     })
  }

  @action('Reply添加附件')
  getReplyAttachList = () => {
     return API.getInitParams(this.initParams).then(res => res)
  }

/*****************************************全部交流*************************************** */
  @action('评论组件的操作')
  getDetailOperate = params => {
    const { data, parent, type: { key, type } } = params;
    this.replyComment = data;
    this.replyCommentParent = parent;
    if (type === 'fabulous') { // 点赞       
      this.wfDiscussOperation(data, parent, 'agree');
    } else if ( type === 'blog-comment') { // 回复      
      this.replyType = 'comment';
      this.placeholderValue = getLabel('385534', '回复')+" "+ data.creater.name;
      if ( !this.commentReplyStoreMap[data.replyId] ) {
        this.commentReplyStoreMap[data.replyId] = new Reply.Store({
          getAttachList: this.getReplyAttachList, 
          // getAtConfig: this.getAtConfig
        });
        this.commentReplyStoreMap[data.replyId].doInit();
      }
     this.communicateReplyVisible(true);
    } else if ( type === 'quote') {  // 引用
      this.replyType = 'quote';  
      this.needPanel = true; 
      this.quoteCancelFlag = false;
      this.quoteInfo = data; //被引用人的信息
      this.placeholderValue = getLabel('512567', '交流内容...');
      if( this.needAttachBtn) {
        this.setAddBtn(this.needAttachBtn);
        if ( !this.quoteReplyStoreMap[data.replyId] ) {
          this.quoteReplyStoreMap[data.replyId] = new Reply.Store({ 
            getAttachList: this.getReplyAttachList,  
            // getAtConfig: this.getAtConfig
          });
        }
      } else {
        if ( !this.quoteReplyStoreMap[data.replyId] ) {
          // this.quoteReplyStoreMap[data.replyId] = new Reply.Store({getAtConfig: this.getAtConfig});
          this.quoteReplyStoreMap[data.replyId] = new Reply.Store();
        }
      }   
      this.quoteReplyStoreMap[data.replyId].doInit();
      this.communicateReplyVisible(true);
    } else if (type === 'delete') {  // 删除
      //交流的删除
      if( key === 'delContent' ) {
        this.currentModel = alert(getLabel('388758', "确认要删除吗？"), '', [
          {text: getLabel('31129', "取消")},
          {text: getLabel('33703', "确认"),
            onPress: () => {
              this.wfDiscussOperation( data, parent, 'delContent')
            }
          }
        ])
      } else if( key === 'delReply' ) {
        this.currentModel = alert(getLabel('512301', "确认要删除该评论吗？"), '', [
          {text: getLabel('31129', "取消")},
          {text: getLabel('33703', "确认"),
            onPress: () => {
              this.wfDiscussOperation( data, parent, 'delReply')
            }
          }
        ])
      }
    } 
  }

  
  @action('删除/点赞操作')
  wfDiscussOperation = (data, parent, val, callback, otherparams) => {
    let params = {
      id: data.contentId,
      operationType: val, 
      communicationId: this.communicationId,
      ...this.initParams
    }
    //删除
    if(val === 'delContent' || val === 'delReply') {
      params.id = data.replyId; //评论的id=id与交流内容的id=contentId
      API.doDelete(params).then( res => {
        this.relatedPage = 1;
        if( res.canDelete && this.page === 'allCommunications') {
            this.allComment.getDatas();
        } else if ( res.canDelete && this.page === 'relatedMe') {
            this.relatedMeComment.getDatas();
        } else {
          Toast.info(getLabel('512478','已超过规定时间或有新内容，无法删除'), 1);
          if(this.page === 'allCommunications') {
            this.allComment.getDatas();
          } else {
            this.relatedMeComment.getDatas();
          }
        }
      }
    )}
    //点赞
    if(val === 'agree') API.doApprove(params).then(res => {
      let approveObj = {};
      this.reflashCurrentPageFlag = true;
      this.getContentList().then(res => {
        approveObj =  res.replyList.filter(v => v.contentId === data.contentId); 
        if(this.page === "allCommunications") {
          this.allComment.doOperateReply({
            replyId: data.replyId,
            parentId: parent ? parent.replyId : '',
            reply: approveObj[0]
          })
        } else {
          this.relatedMeComment.doOperateReply({
            replyId: data.replyId,
            parentId: parent? parent.replyId : '',
            reply: approveObj[0]
          })
        }
      });
    })
    
  }
   
  @action('底部输入框mask点击事件')
  onMaskClick = () => {
    if(this.page === 'relatedMe') {
      this.needPanel = false;
    } else {
      if(this.needPanel) {
        this.communicateReplyVisible(false);
      } else {
        this.replyType = '';
        // this.communicateReply.doClear();
        this.placeholderValue = getLabel('512567', '交流内容...'); 
        this.communicateReplyVisible(false);
      }
    }
    this.setAddBtn(this.needAttachBtn);
  }
 


  @action('签字意见回复或者引用点击面板取消，清理store') 
  clearReplyStore = () => {
    this.communicateReply.doClear();
    if (this.replyComment) {
      this.replyType === 'quote' && this.quoteReplyStoreMap[this.replyComment.replyId].doClear();
    }
   
  }
/*********************************************提交新交流，提交评论******************************** */

  @observable replyParams={}; //回复保存传递的参数
  @observable signReplyText= '';

  @action('保存被回复人的签字意见文本') 
  setReplyMark = (text) => {
    this.signReplyText = text;
  }

  @action('提交保存新交流')
  publishCommunicate = (data = {}) => { 
    let newParams = {};
    this.replyDatas = data.attach;
    this.communicateReply.doClear(); 
    let remark = data.text;
    data.imgList.map((item) => {
      remark = remark + '<img class="communicateImgPlay" src=\"' + item.imgSrc + '\">';
    })
    if(this.signRelyFlag) {
      newParams = {
        "reply_man": this.replyParams.displayname, 
        "log_useid": this.replyParams.displayid,
        "log_displaydepid": this.replyParams.displaydepid,
        "log_displaydepname": this.replyParams.displaydepname,
        "log_operatedate": this.replyParams.log_operatedate,
        "log_operatetime": this.replyParams.log_operatetime,
        "log_nodename": this.replyParams.log_nodename,
        "operationname": this.replyParams.operationname,
        "sign_logid": this.replyParams.logid,
        "signReplyText": this.signReplyText,
        "quote_type": 'quoteSign',
        'log_userType': this.replyParams.displaytype == '0' ? '1' : this.replyParams.displaytype == '1' ? '2' : ''
      }
    }
    let params = {
      communicationId: this.communicationId,
      remark: remark,
      relatedprj: (toJS(this.replyDatas).task && toJS(this.replyDatas).task.map(item => item.id)) || '',
      relatedcus: (toJS(this.replyDatas).customer && toJS(this.replyDatas).customer.map(item => item.id)) || '',
      relatedwf:(toJS(this.replyDatas).workFlow && toJS(this.replyDatas).workFlow.map(item => item.id)) || '',
      relateddoc:(toJS(this.replyDatas).document && toJS(this.replyDatas).document.map(item => item.id)) || '',
      relatedacc:(toJS(this.replyDatas).uploadFile && toJS(this.replyDatas).uploadFile.map(item => item.id)) || '',
      projectIDs:(toJS(this.replyDatas).project && toJS(this.replyDatas).project.map(item => item.id)) || '',
      ...this.initParams,
      ...newParams
    }
    this.relatedPage = 1;
    this.signRelyFlag = false;
   
    API.doSaveContent(params).then( res => {
      this.imageArr = [];
      this.allComment.getDatas();
      this.communicateReplyVisible(false);
      this.replyType = '';
      this.placeholderValue = getLabel('512567', '交流内容...'); 
    })
  }
  
  setBottomButton = () => {
    if(Adapter.judgeApiSupport(AdapterConstant.API_SPEECH_TO_TEXT)) {
      this.leftConfig =[{ type: 'voice'},...this.leftConfig,{ type: 'tianjia'}];  
    } else {
      this.leftConfig =[...this.leftConfig,{ type: 'tianjia'}];  
    }
  }
  @action('回复组件设置添加按钮') 
  setAddBtn = (val) => {
    if(val) {
      if(this.leftConfig.every(v => { return v.type !== 'tianjia'})) {
        this.setBottomButton();
      }
    }
  }
  @action('提交回复评论')
  saveComment = (data, callback) => {
    this.communicateReply.doClear(); 
    this.setAddBtn(this.needAttachBtn);
    this.replyDatas = data.attach;
    let remark = data.text;
    data.imgList.map((item) => {
      remark = remark + '<img class="communicateImgPlay" src=\"' + item.imgSrc + '\">';
    })
    let commentObj = {}; //保存的评论对象
    if(this.replyType === 'quote' && this.quoteCancelFlag && this.page !== 'relatedMe' ) {
      this.quoteCancelFlag = false;
      this.replyType = '';
    }
    let params = {
      communicationId: this.communicationId,
      remark: remark,
      replyType: this.replyComment ? this.replyType : '',
      relatedprj: (toJS(this.replyDatas).task && toJS(this.replyDatas).task.map(item => item.id)) || '',
      relatedcus: (toJS(this.replyDatas).customer && toJS(this.replyDatas).customer.map(item => item.id)) || '',
      relatedwf:(toJS(this.replyDatas).workFlow && toJS(this.replyDatas).workFlow.map(item => item.id)) || '',
      relateddoc:(toJS(this.replyDatas).document && toJS(this.replyDatas).document.map(item => item.id)) || '',
      relatedacc:(toJS(this.replyDatas).uploadFile && toJS(this.replyDatas).uploadFile.map(item => item.id)) || '',
      projectIDs:(toJS(this.replyDatas).project && toJS(this.replyDatas).project.map(item => item.id)) || '',
    }
    if (this.replyComment) {
      this.replyType === 'quote' && this.quoteReplyStoreMap[this.replyComment.replyId].doClear();
      this.replyType === 'comment' && this.commentReplyStoreMap[this.replyComment.replyId].doClear();
    }
   
    if (this.page === 'relatedMe') {
      params = {...params, type:'relatedme'}
    }
    if(this.replyType === 'comment') {
      if(this.replyCommentParent) {
        params = {
          ...params, 
          contentId: this.replyComment ? this.replyComment.contentId : 0,
          replyId: this.replyComment.replyId, receiveUser: this.replyComment.createUser,
          resiveUserType: this.replyComment.createUserType
        }
      } else {
        params = {
          ...params, 
          contentId: this.replyComment ? this.replyComment.contentId : 0,
          replyId: this.replyComment.replyId
        }
      }
      this.replyType = '';
      return API.doSaveReply(params).then(res => {
        this.imageArr = [];
        this.reflashCurrentPageFlag = true; //获取数据为当前页
        this.getContentList().then(res => {
          commentObj =  res.replyList.filter(v => v.contentId === this.replyComment.contentId); 
          this.relatedPage = 1;
          this.page === 'relatedMe' && this.relatedMeComment.getDatas();
          this.page === 'allCommunications' && this.allComment.getDatas();
          // if(this.page  === 'allCommunications') { //如果为全部交流评论或者与我相关评论只刷新有变更的数据,不整体刷新页面
          //   this.allComment.doOperateReply({
          //     replyId: this.replyComment.replyId,
          //     parentId: this.replyCommentParent? this.replyCommentParent.replyId : '',
          //     reply: this.replyCommentParent ? commentObj[0].childReply : commentObj[0]
          //   })
          // } else {
          //   this.relatedMeComment.doOperateReply({
          //     replyId: this.replyComment.replyId,
          //     parentId: this.replyCommentParent? this.replyCommentParent.replyId : '',
          //     reply: this.replyCommentParent? commentObj[0].childReply : commentObj[0] 
          //   })
          // }  
        });
        this.communicateReplyVisible(false);
        this.placeholderValue = getLabel('512567', '交流内容...'); 
      })
    } else if(this.replyType === 'quote') {
      this.replyType = '';  
      let newParams = { 
        ...params, 
        ...this.initParams,  
        contentId: this.replyComment ? this.replyComment.contentId : 0
      };
       return API.doSaveContent(newParams).then( () => {
        this.imageArr = [];
        this.relatedPage = 1;
        this.page === 'relatedMe' && this.relatedMeComment.getDatas();
        this.page === 'allCommunications' && this.allComment.getDatas();
        this.communicateReplyVisible(false);
        this.placeholderValue = getLabel('512567', '交流内容...'); 
      })
    } else if(this.replyType === '') {
      let newParams = { ...params, ...this.initParams};
      API.doSaveContent(newParams).then( res => {
        this.quoteReplyStoreMap[this.replyComment.replyId].doClear();
        this.imageArr = [];
        this.relatedPage = 1;
        this.allComment.getDatas();
        this.communicateReplyVisible(false);
        this.placeholderValue = getLabel('512567', '交流内容...'); 
      })
    }
  }

 /* *****************************相关资源 **************************************/
  @observable resourceMap = {}; //相关资源获取数据
  @action('相关资源数据获取')
  getResource = () => {
    let params = {
      ...this.initParams
    }
    API.getResource(params).then( res => {
      this.resourceMap = res;
    })
  }


  //获取At人员的数据
  initAtData = () => {
    const {requestid} = base.wfGlobalStore.commonParam;
    //避免多次请求
    if(this.reqOperators.length === 0 && requestid > 0) {
        API_REQ.getReqAtUser({requestid}).then((data = {}) => {
            let operators = data.operators || [];
            let reqOperatorIds = [];
            remove(operators,(item)=>{
                let isInclude = includes(reqOperatorIds,item.id);
                if(!isInclude) reqOperatorIds.push(item.id);
                return isInclude;
            });
            this.reqOperators  = operators.slice(0,100);
        })
    }
}

  @action("组件卸载之后清理数据")
  clearStore = () => {
    this.communicateReply && this.communicateReply.doClear();  //清交流组件
    this.replyType === 'quote' && this.quoteReplyStoreMap[this.replyComment.replyId].doClear(); //清除引用组件
    this.relatedPage = 1;
    this.hasLoaded = false;
    this.type = 'list'
    this.needAttachBtn = false;
    this.leftConfig = this.leftConfig.filter(v => {return v.type !== 'tianjia' && v.type !== 'voice'});  
    this.page = 'allCommunications';
  }
  @action('关闭所有弹窗') 
  closeAllModel = () => {
    this.currentModel && typeof this.currentModel.close === 'funciton' && this.currentModel.close();
  }
} 